﻿var DbTypeAll, ControlTypeList, strControlTypeList, BaseUrl = "";
var queryData;//搜索数据
var filter;//高级搜索框
var CodeService = {
    Code: null,
    TableId: 0,
    TableName:"",
    codeEditor:null,
    InitTree: function () {
        $.each(ControlTypeList, function (key, value) {
            if (strControlTypeList != "") {
                strControlTypeList += ";";
            }
            strControlTypeList += key + ":" + value;

        });
       
        $(".codeserver").jstree({
            "core": {
                "check_callback": true,//默认为flase，会导致无法使用修改树结构。
                data: function (node, callback) {
                    var _self = this;
                    var id = node.id;
                    Ajax({
                        url: BaseUrl + "/home/GetTree",
                        data: { parentid: (node.original && node.original.SourceId ? node.original.SourceId : "0"), action: (node.original && node.original.action ? node.original.action : "T"), DbServerType: (node.original && node.original.DbServerType ? node.original.DbServerType : 0) },
                        success: function (result) {
                            if (!node.original) {
                                delete result.parent;
                            }
                            if (node.original && node.original.DbServerType == 2)
                            {
                                for (var i = 0; i < result.length; i++)
                                {
                                    result[i].ProviderType = node.original.ProviderType;
                                }
                            }
                            callback.call(_self, result);
                        }
                    });

                }

            },
            "contextmenu": {
                select_node: true,
                show_at_node: true,
                show_Itemed: function (treeNode, items) {
               
                    var node = treeNode.original;
               
                    items.create._disabled = true;
                    items.edit._disabled = true;
                    items.delete._disabled = true;
                    //items.export._disabled = true;
                    $.each(items, function (key, value) {
                        if (key.indexOf("template")!=-1)
                            delete items[key];
                    });
                   
                    if (node.ProviderType && node.ProviderType==-1) {
                        items.create._disabled = false;
                       
                    }
                    else if ((node.DbServerType ==2 && node.DbTableId) || (node.DbServerType==0&&node.ProviderType>0)) {
                        items.edit.label = "修改";
                        items.edit._disabled = false;
                        items.delete._disabled = false;
                    
                    }
                 
                    if (node.DbServerType == 1 && !node.DbTableId)
                    {
                        var templateRoot = $(".templateTree").jstree("get_node", "000");
                        if (templateRoot.children && templateRoot.children.length > 0)
                        {
                            for (var i = 0; i < templateRoot.children.length; i++) {
                                var template = $(".templateTree").jstree("get_node", templateRoot.children[i]);
                                if (template && template.original)
                                {
                                    var original = template.original;
                                    items[original.TemplateId] = {
                                        "label": original.TemplateName+"模板批量生成",
                                        "icon": "fa fa-plus",
                                        "id": original.TemplateId,
                                        "action": function (treeNode) {
                                            var inst = jQuery.jstree.reference(treeNode.reference);
                                            var node = inst.get_node(treeNode.reference);
                                            
                                            if (!node.state.opened) {
                                                inst.open_node(node);
                                                Notify.Error("请等待，正在加载表.....");
                                                return;
                                            }
                                            if (node.children && node.children.length > 0)
                                            {
                                                var modal = Notify.loading("模板生成中，请稍候.....");
                                                CodeService.CreateCode(inst, node.children, treeNode.item.id, 0, node.children.length, modal);
                                            }
                                            
                                        },
                                    }
                                }
                            }
                           
                        }
                       
                    }
                    return items;
                },
                "items": {
                    "create": {
                        "label": "新增",
                        "icon": "fa fa-plus",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            CodeService.DbServerRemote(inst,treeNode,true);
                        },
                    },
                    "edit": {
                        "label": "修改",
                        "icon": "fa fa-paste",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                           
                            CodeService.DbServerRemote(inst, treeNode, false);
                         
                     
                        }
                    },
                
                    "delete": {
                        "label": "删除",
                        "icon": "fa fa-trash",
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);
                            Notify.Confirm("确定要删除该信息吗？", "删除提示", function () {
                                Ajax({
                                    url: BaseUrl + "/home/DbDelete",
                                    data: { sourceId: node.original.SourceId, dbServerType:node.original.DbServerType},
                                    success: function (result, message) {
                                        tree.delete_node(treeNode.reference);
                                    }
                                });
                            });
           
                        }
                    },
                    //"export": {
                    //    "label": "导出",
                    //    "icon": "fa fa-download",
                    //    "action": function (treeNode) {
                    //        var inst = jQuery.jstree.reference(treeNode.reference);
                    //        var node = inst.get_node(treeNode.reference);
                    //        var url = BaseUrl + "/home/export?id=" + node.original.SourceId;
                    //        $("#linkExport").attr("href",url);
                    //        $("#linkExport")[0].click();
                    //    }
                    //},
                    //"sync": {
                    //    "label": "数据同步",
                    //    "icon": "fa fa-recycle",
                    //    "action": function (treeNode) {
                    //        var inst = jQuery.jstree.reference(treeNode.reference);
                    //        var node = inst.get_node(treeNode.reference);
                           
                    //        Notify.Confirm("数据同步是指两表之间增量更新？", "确认同步", function () {
                    //            var modal = Notify.loading("数据同步中，请稍候.....");
                    //            Ajax({
                    //                url: BaseUrl + "/home/synctabledata",
                    //                data: { tableid: node.original.DbTableId },
                    //                success: function (result) {
                    //                    Notify.Success("数据同步成功");
                    //                },
                    //                complete: function () {
                    //                    modal.modal("hide");
                    //                }
                    //            });
                    //        });
                    //    }
                    //},
                    
                   
                }
            },

            "plugins": ["wholerow", "contextmenu"]
        }).on('activate_node.jstree', function (obj, e) {
            if (e.node.original.DbServerType<2)
            {
                return false;
            }
            if (e.node.original.DbServerType == 2) {
                $(".code-columns").children("a")[0].click();
                CodeService.TableId = e.node.original.SourceId;
                CodeService.TableName = e.node.original.DbTableName;
               CodeService.loadColumns(e.node.original.SourceId, e.node.original.ProviderType);
                return false;
            }
            //if (e.node.original.action == "1") {
            //    $(".code-columns").children("a")[0].click();
            //    CodeService.TableId = e.node.original.SourceId;
            //    CodeService.loadColumns(e.node.original.SourceId, e.node.original.ProviderType);
            //}
            //else {
            //    if (CodeService.TableId != e.node.original.SourceId) {
            //        $(".code-columns").children("a")[0].click();
            //        CodeService.TableId = e.node.original.SourceId;
            //        CodeService.loadColumns(e.node.original.SourceId, e.node.original.ProviderType,true);
            //        setTimeout(function () { CodeService.loadDataSource(e.node.original.SourceId); }, 1000);
            //    }
            //    else {
            //        $(".code-datasource").children("a").trigger("click");
                
                   
            //    }
               
            //}
        
     
        });
        CodeService.loadTemplate();
        $(".code-columns").children("a").on("click", function () {
            CodeService.loadDataSource(CodeService.TableId);
        });
        $(".code-datasource").children("a").on("click", function () {
            CodeService.loadDataSource(CodeService.TableId);
        });
        $("#create-code").height($(".full-height-scroll").height() - 20);
        CodeService.codeEditor = CodeMirror.fromTextArea($("#create-code")[0], {
            mode: 'htmlmixed',     // HMTL混合模式
            indentUnit: 2,  // 缩进单位，默认2
            smartIndent: false,  // 是否智能缩进
            tabSize: 4,  // Tab缩进，默认4
            readOnly: false,  // 是否只读，默认false
            showCursorWhenSelecting: true,
            lineNumbers: true  // 是否显示行号

        });
     
        setTimeout(function () {
            $("#create-code").parent().find(".CodeMirror-sizer").attr("style", "margin-left: 30px; margin-bottom: -16px; border-right-width: 14px; min-height: 26px; min-width: 71.8px; padding-right: 0px; padding-bottom: 0px;");
            $("#create-code").parent().find(".CodeMirror-linenumbers").css({ width: "29px", height: $(".full-height-scroll").height() });
        },1000);
        CodeService.codeEditor.setSize('auto', $(".full-height-scroll").height()-50);
    },
    loadTemplate:function()
    {
        $(".templateTree").jstree({
            "core": {
                "check_callback": true,//默认为flase，会导致无法使用修改树结构。
                data: function (node, callback) {
                    var _self = this;

                    Ajax({
                        url: BaseUrl + "/home/GetTemplate",
                        data: { parentid: (node.original ? node.id : "") },
                        success: function (result) {
                            callback.call(_self, result);
                        }
                    });
                }
            },
            "plugins": ["wholerow", "contextmenu"],
            "contextmenu": {
                select_node: true,
                show_at_node: true,
                show_Itemed: function (treeNode, items) {
                    var node = treeNode.original;
                    items.create._disabled = false;
                    items.edit._disabled = true;
                    items.delete._disabled = true;
                    if (node.TemplateId) {
                        items.edit._disabled = false;
                        items.delete._disabled = false;
                    }

                    return items;
                },
                "items": {
                    "create": {
                        "label": "新增",
                        "icon": "fa fa-plus",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            CodeService.Template(inst, treeNode, true);
                        },
                    },
                    "edit": {
                        "label": "修改",
                        "icon": "fa fa-paste",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            CodeService.Template(inst, treeNode, false);
                        }
                    },

                    "delete": {
                        "label": "删除",
                        "icon": "fa fa-trash",
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);
                            Notify.Confirm("确定要删除该信息吗？", "删除提示", function () {
                                Ajax({
                                    url: BaseUrl + "/DbTemplate/Delete",
                                    data: { deleteKeys: node.original.TemplateId },
                                    success: function (result, message) {
                                        tree.delete_node(treeNode.reference);
                                    }
                                });
                            });

                        }
                    }


                }
            },


        }).on('activate_node.jstree', function (obj, e) {
            CodeService.Ajax(e.node.original.TemplateId);
        });
    },
    DbServerRemote:function(tree, treeNode, isAdd){
        var nodeOriginal = tree.get_node(treeNode.reference).original;
        var node = tree.get_node(treeNode.reference);
      
        var buttons= [{ id: "close", isClose: true, Name: "关闭" }];
        buttons.push({
            id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                var itemKeys = "";
                FormHelper.ajaxSubmit(modal.find(nodeOriginal.DbServerType ==2 ? "#dynamic-DbTable-form" : "#dynamic-DbServer-form"), function (result) {

                    if (isAdd) {
                        tree.deselect_all(false);
                        if (node.state.loaded) {
                            tree.create_node(node.id, result);
                        }
                        if (!node.state.opened) {
                            tree.open_node(treeNode.reference);
                        }
                        tree.select_node(result.id);

                    }
                    else {
                        node.original = result;
                        node.text = result.text;
                        tree.edit_node(treeNode.reference, node);
                    }
                 //   OChart.Ajax(result.id);
                    modal.modal("hide");
                });
                return false;
            }
        });
        var url = BaseUrl+"/home/DbServer?id=" + nodeOriginal.SourceId;
        if (nodeOriginal.DbServerType == 2)
        {
           url = BaseUrl + "/home/DbTable?id=" + nodeOriginal.SourceId;
        }
        Notify.Remote({
            Title: nodeOriginal.DbServerType==0? "服务器设置":"表设置",
            remote: url,
            buttons:buttons,
            loaded: function (modal, id) {
                modal.find(nodeOriginal.DbServerType == 2 ? "#dynamic-DbTable-form" : "#dynamic-DbServer-form").CustomForm({
                    isValidate: true,
                    isTable: false
                });


            }
        });
    },
    Ajax: function (templateid) {
        if (!templateid|| CodeService.TableId <= 0) {
           
            return false;
        }
        Ajax({
            url: BaseUrl + "/home/createcode",
            data: { tableid: CodeService.TableId, templateid: templateid },
            success: function (result) {
                CodeService.codeEditor.setValue(result);
            }
        });
    },
    //加载显示字段
    loadColumns: function (tableid, providerType) {
        var DbTypes = [];
        var strDbType = "";
        var lastselectRowId = "";//最后选中的行id

        $.each(DbTypeAll, function (index, item) {
            if (item.DbProviderId == 1) {
                DbTypes.push({ DbFieldRelationTypeId: item.DbFieldRelationTypeId, DbTypeName: item.DbTypeName, DbProviderId: item.DbProviderId, "SysDbType": 2 });
                if (strDbType != "") {
                    strDbType += ";";
                }
                strDbType += item.DbFieldRelationTypeId + ":" + item.DbTypeName;
            }
        });
        if (tableid <= 0) {
            $("#table_list_Columns").jqGrid({
                url: BaseUrl + "/home/GetColumns",
                datatype: "json",
                mtype: "post",
                sortname: "LastModifyDate",
                sortable: false,
                pgbuttons: false,
                autowidth: true,
                pginput: false,//是否显示跳转的输入框
                prmNames: { page: "pageIndex", rows: "pageSize", sort: "sortName", order: "sortOrder", search: "keyword", nd: "nd", npage: null },
                shrinkToFit: false,
                postData: { 'id': tableid },
                jsonReader: {
                    root: "Rows",
                    page: "pageIndex",
                    total: "Total",
                    records: "records",
                    repeatitems: false,
                    cell: "cell",
                    id: "ColumnId",
                    userdata: "userdata",
                    subgrid: {

                        root: "Rows",

                        repeatitems: true,

                        cell: "cell"

                    }
                },

                rowNum: -1,

                rowList: [1000],

                colModel: [
                    { label: '字段名称', name: 'ColumnName', index: 'ColumnName', edittype: 'text', editable: true, sortable: false, width: 200, editrules: { required: true }, align: 'center' },
                { label: '字段描述', name: 'ColumnCaption', index: 'ColumnCaption', edittype: 'text', editable: true, sortable: false, width: 200, editrules: { required: false }, align: 'center' },
                {
                    label: '数据类型', name: 'DbFieldRelationTypeId', index: 'DbFieldRelationTypeId',edittype: 'select', editable:true, sortable: false, width: 120, editrules: { required: true }, align: 'center', textField: 'DbTypeName'
                   , editoptions: { value: strDbType },
                    formatter: function (cellvalue, options, rowObject) {
                        var text = cellvalue;
                        $.each(DbTypeAll, function (index, item) {
                            if (item.DbFieldRelationTypeId == cellvalue) {
                                text = item.DbTypeName;

                                return true;
                            }
                        });
                        return text;
                    }
                },
               
                { label: '是否是主键', name: 'IsPrimary', index: 'IsPrimary',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '自动增长', name: 'IsIdentifier', index: 'IsIdentifier',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '是否唯一', name: 'IsUnique', index: 'IsUnique',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                  { label: 'Grid显示', name: 'IsGridVisible', index: 'IsGridVisible',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
               
                { label: '编辑显示', name: 'IsEditVisible', index: 'IsEditVisible', edittype: 'checkbox', editable: false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '允许为空', name: 'AllowDBNull', index: 'AllowDBNull',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
             
                {
                    label: '控件类别', name: 'ControlType', index: 'ControlType',edittype: 'select', editable:true, sortable: false, width: 130, align: 'center', textField: 'text',
                    editoptions: { value: strControlTypeList },
                    formatter: function (cellvalue, options, rowObject) {
                        var text = cellvalue;
                        $.each(ControlTypeList, function (key, value) {
                            if (key == cellvalue) {
                                text = value;
                                return true;
                            }
                        });
                        return text;
                    }
                },
                   { label: '允许新增', name: 'AllowInsert', index: 'AllowInsert', edittype: 'checkbox', editable: false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '允许修改', name: 'AllowUpdate', index: 'AllowUpdate', edittype: 'checkbox', editable: false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '最大长度', name: 'MaxLength', index: 'MaxLength', edittype: 'text', editable: true, editrules: { required: false, number: true, minValue: 0 }, sortable: false, width: 80, align: 'center' },
                { label: '小数点', name: 'Scale', index: 'Scale', edittype: 'text', editable: true, sortable: false, width: 80, align: 'center', editrules: { required: false, number: true, minValue: 0 } },
               
                { label: 'Grid宽度', name: 'GridWidth', index: 'GridWidth', edittype: 'text', editable: true, sortable: false, width: 80, align: 'center', editrules: { required: true, number: true, minValue: 0 } },
                { label: '系统字段', name: 'IsSystem', index: 'IsSystem',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
               
                { label: '是否启用', name: 'IsEnabled', index: 'IsEnabled',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '是否排序', name: 'IsSort', index: 'IsSort',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '默认排序', name: 'IsDefaultSort', index: 'IsDefaultSort',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: '是否搜索', name: 'IsFilter', index: 'IsFilter',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                //{ label: '默认搜索', name: 'IsDefaultFilter', index: 'IsDefaultFilter',edittype: 'checkbox', editable:false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter },
                { label: 'Label宽度', name: 'LabelWidth', index: 'LabelWidth', edittype: 'text', editable: true, sortable: false, width: 80, align: 'center', editrules: { required: false, number: true, minValue: 80 } },
                { label: 'Input宽度', name: 'InputWidth', index: 'InputWidth', edittype: 'text', editable: true, sortable: false, width: 80, align: 'center', editrules: { required: false, number: true, minValue: 80 } },
                { label: '排序', name: 'OrderNo', index: 'OrderNo', edittype: 'text', editable: true, sortable: false, width: 80, align: 'center', editrules: { required: false, number: true } },
                { label: 'Icon', name: 'GroupIcon', index: 'GroupIcon', edittype: 'text', editable: true, sortable: false, width: 130, align: 'center' },
                { label: '搜索默认值', name: 'DefaultFilterValue', index: 'DefaultFilterValue', type: 'text', editable: true, sortable: false, width: 120, align: 'center' },
                { label: '格式化', name: 'Format', index: 'Format', edittype: 'text', editable: true, sortable: false, width: 130, align: 'center' },
                { label: '最小值', name: 'Min', index: 'Min', edittype: 'text', editable: true, sortable: false, width: 80, align: 'center', editrules: { required: false, number: true } },
                { label: '最大值', name: 'Max', index: 'Max', edittype: 'text', editable: true, sortable: false, width: 80, align: 'center', editrules: { required: false, number: true } },
                { label: '默认值', name: 'DefaultValue', index: 'DefaultValue', edittype: 'text', editable: true, sortable: false, width: 130, align: 'center' },
                { label: '验证键值', name: 'VaildKey', index: 'VaildKey', edittype: 'text', editable: true, sortable: false, width: 130, align: 'center' },
                { label: '正则', name: 'RegValidate', index: 'RegValidate', edittype: 'text', editable: true, sortable: false, width: 130, align: 'center' },
                 //{
                 //    label: '是否固定列', name: 'IsFrozen', index: 'IsFrozen', edittype: 'checkbox', editable: false, sortable: false, width: 80, align: 'center', formatter: CodeService.formatter
                 //},
                { label: '备注', name: 'Remark', index: 'Remark', edittype: 'text', editable: true, sortable: false, width: 130, align: 'center' },
                { label: '修改人', name: 'LastModifyUserId', index: 'LastModifyUserId', edittype: 'text', editable: false, sortable: false, width: 130, align: 'center' },
                { label: '修改时间', name: 'LastModifyDate', index: 'LastModifyDate', type: 'date', editable: false, sortable: false, width: 200, align: 'center', formatter: 'yyyy-MM-dd hh:mm:ss' },
                ],
                pager: "#pager_list_Columns",
          
                add: false,
                edit: false,
                addtext: 'Add',
                edittext: 'Edit',
                cellEdit: true,
                multiselect: true,
                viewrecords: true,
                recordpos: "right",
                cellurl: BaseUrl + "/home/SaveColumnsCell",
                toolbar:[true,'top'],
                gridComplete: function () {
                   
                    $("#table_list_Columns").find(".check-jgrid-item").on("click", function () {
                        var _self=$(this);
                        var dataForm={ id: _self.attr("data-id")};
                        dataForm[_self.attr("name")]=$(this)[0].checked;
                        Ajax({
                            url: BaseUrl + "/home/SaveColumnsCell",
                            data: dataForm,
                            success: function (result) {
                             
                            }
                        });
                    });
                }

            });
            $("#t_table_list_Columns").css({ "height": "40px", "line-height": "40px", "padding-right": "10px", "padding-top": "5px" });
          
            $("#t_table_list_Columns").append(
             "<button class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' id='btnsyncTable' data-style='zoom-in'><i class='fa fa-recycle'></i>同步表结构</button>"
                + "<button class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' id='btn-column-delete' data-style='zoom-in'><i class='fa fa-recycle'></i>字段删除</button>"
                + "<a class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' style='font-size:12px;' id='btn-column-create-template' data-style='zoom-in'><i class='fa fa-recycle'></i>下载导入模板</a>"
                + "<a class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' style='font-size:12px;' id='btn-table-outputExcel' data-style='zoom-in'><i class='fa fa-recycle'></i>导出Excel</a>"
                + "<a class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' style='font-size:12px;' id='btn-table-outputWord' data-style='zoom-in'><i class='fa fa-recycle'></i>导出Word</a>"
            );
            $("#t_table_list_Columns").find(".btn").css({ "margin-right": "5px", "padding": "6px 12px" });
            var btnladda = $('#btnsyncTable').ladda();
            var btndelete = $('#btn-column-delete').ladda();
            var btncreatetemplate = $('#btn-column-create-template').ladda();
            var btntablestruct = $('#btn-table-outputExcel').ladda();
            var btntableoutputWord = $('#btn-table-outputWord').ladda();
            btncreatetemplate.click(function () {
                if (!CodeService.TableId || CodeService.TableId <= 0) {
                    return;
                }
                var url = BaseUrl + "/home/downTableTemplate/" + CodeService.TableId;
                $("#linkExport").attr("href", url);
                $("#linkExport")[0].click();
            });
            btntablestruct.click(function () {
                if (!CodeService.TableId || CodeService.TableId <= 0) {
                    return;
                }
                var url = BaseUrl + "/home/ExportTable/" + CodeService.TableId;
              
                var formParams = [{ "name": "id", "value": CodeService.TableId }];
                CodeService.Export(url, CodeService.TableName, formParams, btntablestruct, ".xlsx");
            });
            btntableoutputWord.click(function () {
                if (!CodeService.TableId || CodeService.TableId <= 0) {
                    return;
                }
                var url = BaseUrl + "/home/ExportWordTable/" + CodeService.TableId;
                var formParams = [{ "name": "id", "value": CodeService.TableId}];
                CodeService.Export(url, CodeService.TableName, formParams, btntableoutputWord,".docx");
            });
            btnladda.click(function () {
                if (!CodeService.TableId || CodeService.TableId <= 0) {
                    return;
                }

                Notify.Confirm("表结构同步是指表的创建以及增量更新，并不会删除原有字段，如果表已存在，增加新字段时请设置默认值或允许字段为空？", "确认同步", function () {
                    btnladda.ladda('start');
                    Ajax({
                        url: BaseUrl + "/home/syncTableStruct",
                        data: { tableid: CodeService.TableId },
                        success: function (result) {
                            Notify.Success("表结构同步成功");
                        },
                        complete: function () {
                            btnladda.ladda('stop');
                        }
                    });
                }, function () {

                });

            });
            btndelete.click(function () {
                if (!CodeService.TableId || CodeService.TableId <= 0) {
                    return;
                }
                var columns;
                columns = jQuery("#table_list_Columns").jqGrid('getGridParam', 'selarrrow');
                if (!columns || columns.length<=0)
                {
                    return;
                }
                var columnstr = "";
                for (var i = 0; i < columns.length; i++) {
                    if (i > 0)
                    {
                        columnstr += ",";
                    }
                    columnstr += columns[i];
                }
                Notify.Confirm("字段删除只是删除当前数据中的行，并不会删除物理表中的字段？", "确认删除", function () {
                    btnladda.ladda('start');
                    Ajax({
                        url: BaseUrl + "/home/DbColumnDelete",
                        data: { deleteKeys: columnstr },
                        success: function (result) {
                            jQuery("#table_list_Columns").jqGrid("setGridParam", {
                                postData: { 'id': CodeService.TableId },
                                page: 1
                            }).trigger("reloadGrid");
                            Notify.Success("字段删除成功");
                        },
                        complete: function () {
                            btnladda.ladda('stop');
                        }
                    });
                }, function () {

                });

            });
        }
        if (tableid > 0) {
            jQuery("#table_list_Columns").jqGrid("setGridParam", {
                postData: { 'id': tableid },
                page: 1
            }).trigger("reloadGrid");

        }
        //$(window).resize(function () {
        //    $("#table_list_Columns").setGridHeight($(".full-height-scroll").height() - 160);
        //    $("#table_list_Columns").setGridWidth($(".tabs-container").width() - 20);
        //});
        $("#table_list_Columns").setGridHeight($(".full-height-scroll").height() - 160);
        $("#table_list_Columns").setGridWidth($(".tabs-container").width() - 20);
    },
    formatter: function (cellvalue, options, rowObject) {
        return '<input type="checkbox" class="check-jgrid-item"  name="' + options.colModel.name + '" ' + (cellvalue ? "checked" : "") + ' data-id="' + rowObject.ColumnId + '" />'
    },
    //加载数据源
    loadDataSource: function (tableid)
    {
        $("#table_list_DataSource").jqGrid('GridUnload');
        var rowids = $("#table_list_Columns").getDataIDs();
        var colModels = [];
        var searchField = [];
        var sortname = "";
       
        if (rowids.length > 0) {
            for (var i = 0; i < rowids.length; i++) {
     
                var rowData = $("#table_list_Columns").getRowData(rowids[i]);
           
                if ($(rowData.IsGridVisible)[0].checked || rowData.ColumnName.toLowerCase() == "isdeleted") {
                    colModels.push(
                   {
                       label: (rowData.ColumnCaption != "" && rowData.ColumnCaption != " " ? rowData.ColumnCaption : rowData.ColumnName),
                       name: rowData.ColumnName,
                       index: rowData.ColumnName,
                       edittype: 'text',
                       editable: false,
                       sortable: true,
                       width: rowData.GridWidth,
                       align: 'center'
                   });
                   
                }
                if ($(rowData.IsPrimary)[0].checked) {//主键排序
                    sortname = rowData.ColumnName;
                }
                if ($(rowData.IsFilter)[0].checked) {
            
                    var text = rowData.ControlType;
                    searchField.push(
                        { name: rowData.ColumnName,
                        display: (rowData.ColumnCaption && rowData.ColumnCaption != "") ? rowData.ColumnCaption : rowData.ColumnName,
                        type: text,
                        editor:{type:text},
                        value: rowData.DefaultFilterValue
                        });
                   
                }
                

            }
        }
        if (CodeService.TableId <= 0)
        {
            return ;
        }
        $("#table_list_DataSource").jqGrid({
            url: BaseUrl + "/home/DbSourceForGrid",
            datatype: "json",
            mtype: "post",
            sortname: sortname,
            sortable: false,
            pgbuttons: true,
            autowidth: false,
            pginput: true,//是否显示跳转的输入框
            prmNames: { page: "pageIndex", rows: "pageSize", sort: "sortName", order: "sortOrder", search: "keyword", nd: "nd", npage: null },
            shrinkToFit: true,
            postData: { 'id': CodeService.TableId },
            jsonReader: {
                root: "Rows",
                page: "pageIndex",
                total: "PageTotal",
                records: "Total",
                repeatitems: true,
                cell: "cell",
                id: "ColumnId",
                userdata: "userdata",
                subgrid: {
                    root: "Rows",
                    repeatitems: true,
                    cell: "cell"

                }
            },

            rowNum: 20,
            rowList: [20, 50, 100, 200],
            toolbar: [true, 'top'],
            colModel: colModels,
            pager: "#pager_list_DataSource",
            add: false,
            edit: false,
            cellEdit: false,
            viewrecords: true,
            recordpos: "right"
        });
        $("#t_table_list_DataSource").css({ "min-height": "40px", "height": "auto", "padding-right": "10px", "padding-top": "5px" });
        $("#t_table_list_DataSource").append(
            "<input type=\"file\" id='btn-table-import-file' style=\"display:none\" accept=\".csv,.xlsx,xls\" /><button class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' id='btnsyncData'  data-style='zoom-in' style='margin-bottom:5px;'><i class='fa fa-recycle'></i>同步数据</button>"
            + "<a class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' style='font-size:12px;' id='btn-table-import' data-style='zoom-in'>"
            +"<i class= 'fa fa-recycle' ></i> 导入</a>"
            + "<button class='btn ladda-button  btn-primary pull-right btn-rounded btn-outline' id='btnlinkExport'  data-style='zoom-in' style='margin-bottom:5px;'><i class='fa fa-download'></i>导出</button>"
            + "<button class='btn btn-primary pull-right btn-rounded btn-search' id='btn-table-data-Search' style='margin-bottom:5px;'><i class='fa fa-search'></i>高级搜索</button>"
            );
      
        var btnladda = $('#btnsyncData').ladda();
       
        btnladda.click(function () {
            if (!CodeService.TableId || CodeService.TableId <= 0)
            {
                return;
            }
            var modal = Notify.Info({
                id: Notify.Guid(),
                Title: "数据同步是指两表之间增量更新",
                MinWidthShow: true,

                content: "<div class=\"form-group\">"
                    +"<label asp-for=\"syncTableName\" class= \"col-md-3 control-label text-right\" >目标表</label>"
                       +" <div class=\"col-md-9  text-left\">"
                    + "<div class=\"input-group m-b\">"
                    +" <span class=\"input-group-addon\">*</span>"
                    +"<input name='syncTableName' id='syncTableName' class=\"form-control\"  />"
                    + " </div>"
                    + "<span asp-validation-for=\"DbTableName\" class=\"text-danger\"></span>"
                    + "</div>"
                +"</div >",
                buttons: [
                    {
                        id: "close", isClose: true, Name: "关闭", click: function () {
                            modal.remove();
                        },
                    },
                    {
                        id: "btnConfirm", isClose: false, Name: "确认同步", click: function () {
                            btnladda.ladda('start');
                            var syncTableName= modal.find("input[name='syncTableName']").val();
                            Ajax({
                                url: BaseUrl + "/home/syncTableData",
                                timeout: 1000000,
                                data: { tableid: CodeService.TableId, Group: queryData, targgetTableName: syncTableName},
                                success: function (result) {
                                  
                                },
                                complete: function () {
                                    btnladda.ladda('stop');
                                }
                            });
                            return true;
                        }
                    },
                ]
            });
         
        });
        var btnImport= $("#btn-table-import").ladda();
        $("#btn-table-import").on("click", function () {
            if (!CodeService.TableId || CodeService.TableId <= 0) {
                return;
            }
            $("#btn-table-import-file").click();
        });
        $("#btn-table-import-file").change(function () {
            if (!CodeService.TableId || CodeService.TableId <= 0) {
                return;
            }
            btnImport.ladda('start');
            var formData = new FormData();
            var name = $("#btn-table-import-file").val();
            formData.append("file", $("#btn-table-import-file")[0].files[0]);
            formData.append("id", CodeService.TableId);
            Ajax({
                url: BaseUrl + "/home/import",
                data: formData,
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                // 告诉jQuery不要去设置Content-Type请求头
                ContentType: false,
              
                success: function (result) {
                    Notify.Success("导入成功");
                    btnImport.ladda('stop');
                },
                error: function (msg) {
                    btnImport.ladda('stop');
                    Notify.Error(msg);
                }
            });
          
         
        });
        queryData = null;
        var export1 = $('#btnlinkExport').ladda();
        export1.click(function () {
            if (!CodeService.TableId || CodeService.TableId <= 0) {
                return;
            }
            var formParams = [];
            if (queryData != null) {
                formParams.push({ "name": "groupWhere", "value": JSON.stringify(queryData) });
            }
            formParams.push({ "name": "id", "value": tableid });
            formParams.push({ "name": "sortName", "value": $("#table_list_DataSource").jqGrid('getGridParam').postData["sortName"] });
            formParams.push({ "name": "sortOrder", "value": $("#table_list_DataSource").jqGrid('getGridParam').postData["sortOrder"] });
            CodeService.Export(BaseUrl + '/home/export',  CodeService.TableName, formParams, export1,".xlsx");
            //var url = BaseUrl + "/home/export?id=" + CodeService.TableId;
            //$("#linkExport").attr("href", url);
            //$("#linkExport")[0].click();
        });
       
        $("#btn-table-data-Search").click(function () {
            filter= QSFilter.InitFilter("table_list_DataSource", searchField, function (data) {
                queryData = data;
                jQuery("#table_list_DataSource").jqGrid("setGridParam", {
                    postData: { 'id': CodeService.TableId, Group: data },
                    page: 1
                }).trigger("reloadGrid");
              
            });
            if (!queryData || !queryData.op)
            {
                filter.addRule($(filter.RuleContainer.children(":eq(0)")));
            }
            if (queryData)
            {
                QSFilter.setData(queryData);
            }
          
        });
        $(window).resize(function () {
            $("#t_table_list_DataSource").find(".btn").css({ "margin-right": "5px", "padding": "6px 12px" });
            $("#table_list_DataSource").setGridHeight($(".full-height-scroll").height() - 160);
            $("#table_list_DataSource").setGridWidth($(".tabs-container").width() - 20);
        });
        $("#t_table_list_DataSource").find(".btn").css({ "margin-right": "5px", "padding": "6px 12px" });
        $("#table_list_DataSource").setGridHeight($(".full-height-scroll").height() - 160);
        $("#table_list_DataSource").setGridWidth($(".tabs-container").width() - 20);
      
    },
    Export: function (url,fileName,formParams,ladda,fileType) {

        var xhr = new XMLHttpRequest();
        var form = new FormData();
        if (ladda != null) {
            ladda.ladda("start");
        }
      
        for (var i in formParams) {
            form.append(formParams[i].name, formParams[i].value);
        }
      
        xhr.open('Post', url, true);        // 也可以使用POST方式，根据接口
        xhr.responseType = "blob";    // 返回类型blob
        // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
        xhr.onload = function () {
            // 请求完成
            if (this.status === 200) {
                // 返回200
                var blob = this.response;
                var reader = new FileReader();
                reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
                reader.onload = function (e) {
                    // 转换完成，创建一个a标签用于下载
                    var a = document.createElement('a');
                    console.log(e);
                    a.download = fileName + "_" + new Date().format("yyyyMMddHHmm") + fileType;
                    a.href = e.target.result;
                    $("body").append(a);    // 修复firefox中无法触发click
                    a.click();
                    $(a).remove();
                    if (ladda != null) {
                        ladda.ladda('stop');
                    }
                }
            }
            
        };

        // 发送ajax请求
        xhr.send(form)
    },
    //导入
    Import: function (tableid, group, ladda) {

    },
    ///模板
    Template: function (tree, treeNode, isAdd)
    {
        var nodeOriginal = tree.get_node(treeNode.reference).original;
        var node = tree.get_node(treeNode.reference);
        var dataeditor;
        var buttons = [{ id: "close", isClose: true, Name: "关闭" }];
        buttons.push({
            id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                var itemKeys = "";
   
                $("#DataTContent").val(dataeditor.getValue());
                FormHelper.ajaxSubmit(modal.find("#dynamic-template-form"), function (result) {

                    if (isAdd) {
                        tree.deselect_all(false);
                        if (node.state.loaded) {
                            tree.create_node(node.id, result);
                        }
                        if (!node.state.opened) {
                            tree.open_node(treeNode.reference);
                        }
                        tree.select_node(result.id);

                    }
                    else {
                        node.original = result;
                        node.text = result.text;
                        tree.edit_node(treeNode.reference, node);

                    }
                    //   OChart.Ajax(result.id);
                    modal.modal("hide");
                });
                return false;
            }
        });
        var url = BaseUrl + "/DbTemplate/_Edit?id=" + node.id;
        if (isAdd) {
            url = BaseUrl + "/DbTemplate/_Edit?ParentId=" + (nodeOriginal.TemplateId? nodeOriginal.TemplateId:"");
        }
        Notify.Remote({
            Title:"模板设置",
            remote: url,
            buttons: buttons,
            loaded: function (modal, id) {
                modal.find("#dynamic-template-form" ).CustomForm({
                    isValidate: true,
                    isTable: false
                });
                dataeditor = CodeMirror.fromTextArea($("#DataTContent")[0], {
                    mode: 'htmlmixed',     // HMTL混合模式
                    height: '400',
                    indentUnit: 2,  // 缩进单位，默认2
                    smartIndent: false,  // 是否智能缩进
                    tabSize: 4,  // Tab缩进，默认4
                    readOnly: false,  // 是否只读，默认false
                    showCursorWhenSelecting: true,
                    lineNumbers: true  // 是否显示行号

                });
                dataeditor.setSize("auto","350");
                dataeditor.setValue($("#DataTContent").val());

            }
        });
    },
    ///批量生成模板
    CreateCode: function (tree,tables, templateid, round, maxtable, modal) {
        var tableid = "";
        if (maxtable <= 0)
        {
            return ;
        }
        if (round >= maxtable) {
            return;
        }
        tableid += tables[round].replace("_DT", "");
       
        Ajax({
            url: BaseUrl + "/home/createcodes",
            data: { tableid: tableid, templateid: templateid, round: round+1, maxtable: maxtable},
            success: function (result) {
                var node = tree.get_node(tables[round]);
                modal.find(".modal-body").html('<i class="fa fa-spinner fa-spin pull-left"></i>代码生成到第' + (round+1) + '表,表名：' + node.text + '，请耐心等待......');
                CodeService.CreateCode(tree, tables, templateid, round + 1, maxtable, modal);
             
                if (maxtable == round+1)
                {

                    $("#linkExport").attr("href","/static/cloud/"+ result);
                    $("#linkExport")[0].click();
                    modal.modal("hide");
                }
            },
            error: function (msg) {
                Notify.Error(msg);
                modal.modal("hide");
            }
        });
    },
  
}
$.fn.modal.Constructor.prototype.enforceFocus = function () { };